package com.kning.poiword.replace;

import com.kning.poiword.constants.ChartTypeConstant;
import com.kning.poiword.model.Chart;
import com.kning.poiword.model.Picture;
import com.kning.poiword.model.Table;
import com.kning.poiword.model.Text;
import com.kning.poiword.utils.RefreshChartDataSouseTools;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieSer;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.FileInputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : 王康宁
 * @version : 1.0
 * @date : 2020/1/6
 **/
public class ReplaceDocComponentImpl implements ReplaceDocComponent {

    private static final int FIRST_INDEX = 0;

    private static final int POSITION = 1;

    private static final int DEFAULT_WIDTH = 200;

    private static final int DEFAULT_HEIGHT = 200;


    @Override
    public void replaceText(List<Text> text, XWPFDocument document) {
        Map<String, String> textMap = text.stream()
                .collect(Collectors.toMap(Text::getMark, Text::getContent));
        doParagraphs(textMap, document);
    }

    @Override
    public void replacePicture(List<Picture> picture, XWPFDocument document) {
        Map<String, String> pictureMap = picture.stream()
                .collect(Collectors.toMap(Picture::getMark, Picture::getUrl));
        //todo width 和 height 别写死呀
        doParagraphs(pictureMap, document, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

    @Override
    public void replaceTable(List<Table> table, XWPFDocument document) {
        //todo 懒得做！
        //todo 自动合并单元格
    }

    @Override
    public void replaceChart(Chart chart, POIXMLDocumentPart poixmlDocumentPart) {
        //todo 解析chartType
        replaceChart(chart, ChartTypeConstant.PIECHART, poixmlDocumentPart);
    }

    @Override
    public void replaceChart(Chart chart, Integer chartType, POIXMLDocumentPart poixmlDocumentPart) {
        switch (chartType) {
            case ChartTypeConstant.BARCHART: {
                //todo  大后天写
                doReplaceBarChart(poixmlDocumentPart, chart);
            }
            break;
            case ChartTypeConstant.PIECHART: {
                //todo  后天写
                doReplacePieChart(poixmlDocumentPart, chart.getTitleArr(), chart.getFldNameArr(), chart.getDataList());
            }
            break;
            default:
                throw new IllegalStateException("Unexpected value: " + chartType);
        }
    }

    //--------------------------------------------------------------------------------//
    // Description:TODO
    // Date：2020/1/7
    //--------------------------------------------------------------------------------//


    protected void doParagraphs(Map<String, String> replaceMap, XWPFDocument document) {
        doParagraphs(replaceMap, document, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

    protected void doParagraphs(Map<String, String> replaceMap, XWPFDocument document, Integer picWidth, Integer picHeight) {
        List<XWPFParagraph> paragraphList = document.getParagraphs();
        if (!CollectionUtils.isEmpty(paragraphList)) {
            paragraphList.forEach(t -> {
                List<XWPFRun> runs = t.getRuns();
                runs.forEach(m -> {
                    String text = m.getText(0);
                    if (text != null) {
                        // 替换文本信息
                        String tempText = text;
                        String key = tempText.replaceAll("\\{\\{", "").replaceAll("}}", "");
                        if (!StringUtils.isEmpty(replaceMap.get(key))) {
                            m.setText(replaceMap.get(key), 0);
                        }

                        // 替换图片内容
                        String tempImgText = text;
                        String imgkey = tempImgText.replaceAll("\\{\\{@", "").replaceAll("}}", "");
                        if (!StringUtils.isEmpty(replaceMap.get(imgkey))) {
                            String imgPath = replaceMap.get(imgkey);
                            try {
                                m.setText("", 0);
                                m.addPicture(new FileInputStream(imgPath), Document.PICTURE_TYPE_PNG, "img.png", Units.toEMU(200), Units.toEMU(200));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            });
        }
    }

    private void doReplaceBarChart(POIXMLDocumentPart poixmlDocumentPart, Chart chart) {


    }

    protected void doReplacePieChart(POIXMLDocumentPart poixmlDocumentPart,
                                     List<String> titleArr, List<String> fldNameArr, List<Map<String, String>> listItemsByType) {
        XWPFChart chart = (XWPFChart) poixmlDocumentPart;
        chart.getCTChart();

        //根据属性第一列名称切换数据类型
        CTChart ctChart = chart.getCTChart();
        CTPlotArea plotArea = ctChart.getPlotArea();

        CTPieChart pieChart = plotArea.getPieChartArray(FIRST_INDEX);
        List<CTPieSer> pieSerList = pieChart.getSerList();  // 获取饼图单位

        RefreshChartDataSouseTools.refreshExcel(chart, listItemsByType, fldNameArr, titleArr);
        RefreshChartDataSouseTools.refreshPieStrGraphContent(pieChart, pieSerList, listItemsByType, fldNameArr, POSITION);
    }


}
